import MyTable from "@/components/MyTable";
import SearchHeader from "@/components/SearchHeader";
import useTable from "@/hooks/useTable";
import { Button, Form, Popconfirm, message } from "antd";
import { useMemo, useRef } from "react";
import { useConfig } from "./form.config";

import { useBoolean, useRequest } from "ahooks";
import Add from "./Add";
import ButtonGroup from "@/components/ButtonGroup";
import { delRoom, getRoomPage } from "@/services/room/room";
import { RoomStatusEnum } from "@/constants/enum";

export default () => {
  const config = useConfig();
  const [form] = Form.useForm();
  const [open, { toggle: toggleOpen }] = useBoolean(false);
  const idRef = useRef(null);

  const { tableProps, reset, submit, refresh } = useTable(getRoomPage, {
    defaultFormValues: {},
    form: form,
  });
  const { run: del } = useRequest(delRoom, {
    manual: true,
    onSuccess: () => {
      message.success("删除成功");
      refresh();
    },
  });

  const addOrEdit = (id: any = null) => {
    idRef.current = id;
    toggleOpen();
  };

  const columns = useMemo(() => {
    return [
      {
        title: "楼层名字",
        dataIndex: "floorName",
      },
      {
        title: "房间号",
        dataIndex: "roomNum",
      },
      {
        title: "房间类型",
        dataIndex: "roomTypeName",
      },
      {
        title: "价格(元/天)",
        dataIndex: "roomPrice",
        render:(r:any)=>`${r}`,
      },
      {
        title: "当前状态",
        dataIndex:'occupied',
        render:(r:any)=>RoomStatusEnum[r]
      },
      {
        title: "操作",
        dataIndex: "action",
        align: "center",
        render: (_: any, record: { roomId: number }) => {
          const { roomId } = record;
          return (
            <ButtonGroup>
              <Button type="link" onClick={() => addOrEdit(roomId)}>
                修改
              </Button>
              <Popconfirm
                placement="topLeft"
                title={"确认删除吗？"}
                okText="确认"
                cancelText="取消"
                onConfirm={() => del([roomId])}
              >
                <Button type="link">删除</Button>
              </Popconfirm>
            </ButtonGroup>
          );
        },
      },
    ];
  }, []);

  return (
    <>
      <div style={{ marginBottom: "16px" }}>
        <SearchHeader
          configs={config}
          form={form}
          onSubmit={submit}
          onReset={reset}
        />
      </div>

      <MyTable
        top={
          <div>
            <Button onClick={() => addOrEdit(null)} type="primary">
              新增客房
            </Button>
          </div>
        }
        rowKey={"roomId"}
        columns={columns}
        {...tableProps}
      />
      {open && (
        <Add
          open={open}
          close={toggleOpen}
          refresh={refresh}
          id={idRef.current}
        />
      )}
    </>
  );
};
